//
//  YDHelpFeedbackController.m
//  CRM
//
//  Created by ios on 16/11/8.
//  Copyright © 2016年 YD_iOS. All rights reserved.
//

#import "YDHelpFeedbackController.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "AFNetworking.h"
#import "CustomSheetView.h"

@interface YDHelpFeedbackController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,UITextFieldDelegate,CustomSheetViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *hintLabel;
@property (weak, nonatomic) IBOutlet UILabel *textCountLabel;
@property (weak, nonatomic) IBOutlet UITextView *contentTextView;
@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

@property (weak, nonatomic) IBOutlet UIImageView *imageView1;
@property (weak, nonatomic) IBOutlet UIImageView *imageView2;
@property (weak, nonatomic) IBOutlet UIImageView *imageView3;
@property (weak, nonatomic) IBOutlet UIImageView *imageView4;
@property (weak, nonatomic) IBOutlet UIButton *addImageButton;
@property (nonatomic, assign) NSInteger addButtonIndex;
@property (nonatomic, copy) NSString *imgpath;

@end

@implementation YDHelpFeedbackController

- (instancetype)init
{
    if (self = [super init]) {
        _addButtonIndex = 0;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
}

- (void)setupView
{
    self.title = @"意见反馈";
    
    self.contentTextView.delegate = self;
   
    self.phoneTextField.delegate = self;
    
    [self.submitButton setBackgroundImage:[UIImage imageNamed:@"btn_Submit_n"] forState:UIControlStateNormal];
    [self.submitButton setBackgroundImage:[UIImage imageNamed:@"btn_Submit_c"] forState:UIControlStateHighlighted];

    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewClick)];
    [self.view addGestureRecognizer:tap];
    
}

- (void)viewClick
{
    [self.view endEditing:YES];
}

#pragma mark 点击添加图片
- (IBAction)addImageButtonClick:(UIButton *)sender {
    
    CustomSheetView *sheet = [[CustomSheetView alloc] initWithBottomButtonCount:1 otherButtonTitleArray:@[@"拍摄",@"从相册中选择"]];
    sheet.delegate = self;
    [kWindow addSubview:sheet];
}

- (void)actionSheetDidSelect:(NSInteger)index
{
    if (index == 0 || index == 1) {
        //1：相机 2：相册
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}

#pragma mark 提交按钮点击
- (IBAction)submitButtonClick:(UIButton *)sender
{
    [self.view endEditing:YES];
    
    if (self.contentTextView.text.length <= 0) {
        [MBProgressHUD showTips:@"问题和内容不能为空" toView:self.view];
        return;
    }
    
    NSDictionary *dic = @{@"content" : self.contentTextView.text,
                          @"phone" : self.phoneTextField.text,
                          @"imgpath" : _imgpath,
                          @"source" : @"TRIAL"
                          };
    NSString *url = [NSString stringWithFormat:@"%@sid=%@", kFeedbackAddress, getNSUser(kAPP_SID)];
    
    [YDDataService POST:dic url:url block:^(id result) {
        
        [MBProgressHUD showTips:@"反馈成功" toView:kWindow];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });

    } failBlock:^(id error) {
        
    }];
                 
}

#pragma mark  - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    NSInteger currentCount = (unsigned long)textView.text.length - range.length + text.length;
    self.textCountLabel.text = [NSString stringWithFormat:@"%lu/200", currentCount];
    self.hintLabel.text = currentCount == 0 ? @"请输入您遇到的问题和建议..." : @"";

    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self.view endEditing:YES];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    
    return YES;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.phoneTextField) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }
    
    return YES;
}


#pragma mark - 图片部分
//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage *selectImage = info[UIImagePickerControllerOriginalImage];
        
        _addButtonIndex++;
        
        //如果是图片
        switch (_addButtonIndex) {
            case 1:
                self.imageView1.image = info[UIImagePickerControllerOriginalImage];
                break;
            case 2:
                self.imageView2.image = info[UIImagePickerControllerOriginalImage];
                break;
            case 3:
                self.imageView3.image = info[UIImagePickerControllerOriginalImage];
                break;
            case 4:
                self.imageView4.image = info[UIImagePickerControllerOriginalImage];
                break;
            default:
                break;
        }
        
        
        //压缩图片
        NSData *fileData = UIImageJPEGRepresentation(selectImage, 0.1);
        
        //获取正在编辑的图片
        
        __block NSURL *imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL];
        
        __block NSString *imageName;
        //获取图片的名字信息
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
        {
            ALAssetRepresentation *representation = [myasset defaultRepresentation];
            imageName = [representation filename];//self.imageName是属性
            //上传图片
            [self uploadImageWithData:fileData imageName:imageName];
        };
        
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:imageUrl
                       resultBlock:resultblock
                      failureBlock:nil];
        
        [self dismissViewControllerAnimated:YES completion:^{
            switch (_addButtonIndex) {
                case 1:
                {
                    self.addImageButton.frame = self.imageView2.frame;
                }
                    break;
                case 2:
                {
                    self.addImageButton.frame = self.imageView3.frame;
                }
                    break;
                case 3:
                {
                    self.addImageButton.frame = self.imageView4.frame;
                }
                    break;
                case 4:
                {
                    self.addImageButton.frame = CGRectZero;
                }
                    break;
                default:
                    break;
            }
            
        }];
    }

}

- (void)uploadImageWithData:(NSData *)fileData imageName:(NSString *)imageName
{
    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.上传文件
    NSDictionary *dict = @{};
    
    NSString *urlString = [NSString stringWithFormat:@"%@sid=%@", kAddImageAddress, getNSUser(kAPP_SID)];;
    
    [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //这个就是参数-
        [formData appendPartWithFileData:fileData name:@"file" fileName:imageName mimeType:@"image/png"];
 
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //请求成功
        NSLog(@"请求成功：%@",responseObject);
        
        if ([[responseObject valueForKey:@"code"] isEqualToString:@"S_OK"]) {
            NSString *responseImageName = [responseObject valueForKey:@"var"];
            switch (_addButtonIndex) {
                case 1:
                    _imgpath = responseImageName;
                    break;
                case 2:
                    _imgpath = [NSString stringWithFormat:@"%@, %@", _imgpath, responseImageName];
                    break;
                case 3:
                    _imgpath = [NSString stringWithFormat:@"%@, %@", _imgpath, responseImageName];
                    break;
                case 4:
                    _imgpath = [NSString stringWithFormat:@"%@, %@", _imgpath, responseImageName];
                    break;
                default:
                    break;
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败
        NSLog(@"请求失败：%@",error);
    }];
    
}





#warning 下面这些都没用
#pragma mark 获得所有相簿的原图
- (void)getOriginalImages
{
    // 获得所有的自定义相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    // 遍历所有的自定义相簿
    for (PHAssetCollection *assetCollection in assetCollections) {
        [self enumerateAssetsInAssetCollection:assetCollection original:YES];
    }
    
    // 获得相机胶卷
    PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
    // 遍历相机胶卷,获取大图
    [self enumerateAssetsInAssetCollection:cameraRoll original:YES];
}


#pragma mark 获得所有相簿中的缩略图
- (void)getThumbnailImages
{
    // 获得所有的自定义相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    // 遍历所有的自定义相簿
    for (PHAssetCollection *assetCollection in assetCollections) {
        [self enumerateAssetsInAssetCollection:assetCollection original:NO];
    }
    // 获得相机胶卷
    PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
    [self enumerateAssetsInAssetCollection:cameraRoll original:NO];
}


/**
 *  遍历相簿中的所有图片
 *  @param assetCollection 相簿
 *  @param original        是否要原图
 */
- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original
{
    NSLog(@"相簿名:%@", assetCollection.localizedTitle);
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = YES;
    
    // 获得某个相簿中的所有PHAsset对象
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    for (PHAsset *asset in assets) {
        // 是否要原图
        CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
        
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            NSLog(@"%@", result);
        }];
    }
}


@end
